package learn.ch1.connection;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description todo
 * @Author yusj
 * @Date 2021/12/14
 * @Version 1.0
 */
public class DbPool {
    private LinkedList<Connection> pool=new LinkedList<Connection>();


    public DbPool(int size){
        synchronized (pool){
            for(int i=0;i<size;i++){
                pool.addLast(SqlConn.fetchConn());
            }
        }
    }


    public Connection getConnection(long over){
        synchronized (pool){
            //不超时，那就一直等待。
            if(over==0){
                while(pool.size()==0){
                    try {
                        pool.wait();
                    } catch (InterruptedException e) {
                        return null;
                    }
                }
                if(pool.isEmpty()){
                    return null;
                }
                return pool.removeFirst();
            }else{
                long overTime=System.currentTimeMillis()+over;
                long remain=over;
                while(pool.isEmpty()&&remain>0){
                    try {
                        //todo  **** 此处是关键，等待 remain 时间。
                        pool.wait(remain);
                        remain=overTime-System.currentTimeMillis();
                    } catch (InterruptedException e) {
                        return null;
                    }
                }
                if(pool.isEmpty()){
                    return null;
                }
                return pool.removeFirst();
            }
        }
    }


    public void releaseConn(Connection conn){
        synchronized (pool){
            pool.addLast(conn);
            pool.notifyAll();
        }
    }

    @Override
    public String toString() {
        return "DbPool{" +
                "pool=" + pool.isEmpty() +
                '}';
    }

    public static void main(String[] args) {
        //连接池  5 个链接

        DbPool pool=new DbPool(5);

        //获取到链接的数量
        AtomicInteger got=new AtomicInteger();
        //没获取到链接的数量
        AtomicInteger noGot=new AtomicInteger();

        //等待500ms
        long waitTime=500;

        CountDownLatch  count=new CountDownLatch(6);


        //5 个能取到  1个取不到。
        for(int i=0;i<6;i++){
            new Thread(new Worker(pool,got,noGot,count,waitTime),"th"+i).start();
        }

        try {
            count.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("got:"+got+"，not got:"+noGot);

    }

}
